<template>
  <div class="pagination">
    <h1>{{ startNumAndEndNum }}--当前页码{{ pageNo }}</h1>
    <!-- 连续页面前面部分的控制显示 -->
    <button :disabled="pageNo == 1" @click="$emit('getpageNo', pageNo - 1)">
      上一页
    </button>
    <button
      v-if="startNumAndEndNum.start > 1"
      @click="$emit('getpageNo', 1)"
      :class="{ active: pageNo == 1 }"
    >
      1
    </button>

    <button v-if="startNumAndEndNum.start >= 3">···</button>

    <!--中间部分连续页码动态渲染 渲染的页面只显示>=连续页面的start-->
    <button
      v-for="(page, index) in startNumAndEndNum.end"
      :key="index"
      v-if="page >= startNumAndEndNum.start"
      @click="$emit('getpageNo', page)"
      :class="{ active: pageNo == page }"
    >
      {{ page }}
    </button>

    <!-- 连续页面后面部分的控制显示 -->
    <button v-if="startNumAndEndNum.end < totaPage - 1">···</button>
    <button
      v-if="startNumAndEndNum.end < totaPage"
      @click="$emit('getpageNo', totaPage)"
      :class="{ active: pageNo == totaPage }"
    >
      {{ totaPage }}
    </button>
    <button
      :disabled="pageNo == totaPage"
      @click="$emit('getpageNo', pageNo + 1)"
    >
      下一页
    </button>
    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ["pageNo", "pageSize", "total", "continues"],
  // 总共多少页
  computed: {
    totaPage() {
      //向上取整
      return Math.ceil(this.total / this.pageSize);
    },

    // 计算连续的的页码的初始与结束页码数字
    startNumAndEndNum() {
      // 定义的数据引入
      const { continues, pageNo, totaPage } = this;
      // 定义2个变量储存开始与结束页面
      let start = 0,
        end = 0;

      // 连续页面至少5页（若数据较少则不够5页）2中情况
      if (continues > totaPage) {
        // 数据和页面较少时
        start = 1;
        end = totaPage;
      } else {
        // 正常情况，数据较多，总页码大于连续显示页面
        //连续页码开始页面=当前页数-（连续页码页面数-1）/2
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);

        //如果当前页面（pageNo）较小时，以上方法可能会出现 start<=0的问题
        if (start < 1) {
          //开始页为1，结束页分页器连续页码的个数continues
          start = 1;
          end = continues;
          //如果当前页面（pageNo）较大时,会出现end>总页数的情况
        }
        if (end > totaPage) {
          end = totaPage;
          start = totaPage - continues + 1;
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="scss" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}

</style>